<html>

	<head>
		<title></title>
		<title>智管家－专注快消品行业服务商</title>
		<link rel="bookmark" type="image/x-icon" href="http://qiniudns01.zhelan.net/favicon.ico" />
		<link rel="shortcut icon" href="http://qiniudns01.zhelan.net/favicon.ico" type="image/x-icon">
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<meta http-equiv="Cache-Control" content="no-cache,must-revalidate" />
		<link href="../../css/dialog.css" rel="stylesheet">

		<link href="../../css/skin/default/pagination.css" rel="stylesheet" type="text/css" />
		<link href="../../css/skin/default/style.css" rel="stylesheet" type="text/css" />

		<script src="../../js/lib/jquery/jquery-1.10.2.min.js" type="text/javascript"></script>

		<link href="../../js/lib/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
		<script src="../../js/lib/ligerUI/js/ligerui.all.js" type="text/javascript"></script>
		<script src="../../js/lib/ligerUI/js/plugins/ligerComboBox.js" type="text/javascript"></script>

		<script type="text/javascript" src="../../js/JS/jquery.lazyload.min.js"></script>

		<script type="text/javascript" src="../../js/JS/layout.js"></script>
		<script type="text/javascript" src='../../js/plupload/plupload.full.min.js'></script>
		<script src="https://cdn.bootcss.com/json3/3.3.2/json3.min.js"></script>
		<script src="../../js/dialog.js"></script>
		<script src="../../js/JS/layout.js"></script>
		<script src="../../js/constants.js" type="text/javascript"></script>
		<script src="../../js/api.js" type="text/javascript"></script>
		<script src="../../js/qiulib/qiniu.min.js"></script>
		<script type="text/template" class="record_row">
			<li style="border-bottom: 1px solid #f1f1f1;" id={liid}>
				<div id="img" class="aui-li-detail" style="text-align: left;width: 30%;float: left;">{Fname}</div>
				<div class="aui-li-detail" style="text-align: center;width: 10%;float: left;">{Fsize}</div>
				<div class="aui-li-detail" style="text-align: center;width: 50%;float: left;">
					<div class="progress_sku">
						<div class="progress" id="{Fpg}"><span style="margin-left:10px;float:left;height: 15px; line-height: 15px; color:#fff">0%</span></div>
					</div>
				</div>
			</li>
		</script>
	</head>
	<style>
		.aui-li-detail {
			font-size: 8px;
			min-height: 26px;
			line-height: 26px;
		}
		
		.progress_sku {
			border: 1px solid #f1f1f1;
			border-radius: 15px;
			-moz-border-radius: 15px;
			height: 15px;
			width: 100%;
			margin-top: 2px;
			/* Old Firefox */
		}
		
		.progress {
			border: 1px solid;
			border-radius: 15px;
			-moz-border-radius: 15px;
			background: #31B807;
			height: 15px;
			width: 0%;
			/* Old Firefox */
		}
	</style>
	<script type="text/javascript">
		var board = {};
		var managerSPhotos, managerPhoto;
		var comboxDefault = "";

		var attrUrl = BaseUrl + "Attach?token=" + $api.getStorage("token")

		var attrTypeUrl = BaseUrl + "AttachType?token=" + $api.getStorage("token")
		var token;
		var domain;

		var config = {
			useCdnDomain: true,
			disableStatisticsReport: false,
			retryCount: 6,
			region: qiniu.region.z0
		};
		var putExtra = {
			fname: "",
			params: {},
			mimeType: null
		};
		var user = $api.getStorage("user");
		var xc = $api.getStorage(user.Fid + "_xc");
		$(function() {
			imgLayout();
			initQiuniu();
			$(window).resize(function() {
				imgLayout();
			});

			managerSPhotos = $("#ddlSPhotos").ligerComboBox({
				url: attrTypeUrl,
				ajaxType: 'get',
				valueField: 'Fid',
				textField: 'Fname',
				onSelected: function(newvalue) {

					comboxDefault = newvalue;
					$api.setStorage(user.Fid + "_xc", newvalue);
					initImgListNet();
				}
			});
			if(!$api.isEmpty(xc)) {

				comboxDefault = xc;
				managerSPhotos.setValue(xc);
			} else {

				managerSPhotos.setValue(0);
				comboxDefault = 0;
			}

		});
		//////////////////////////////////////////////////////////
		function initQiuniu() {
			var url = BaseUrl + "Qiniu?token=" + $api.getStorage("token");
			$api.ajaxapp2(url, {}, function(res) {
				token = res.Token;
				domain = res.DoMain;
				initUpView();
			});
		}
		var BLOCK_SIZE = 4 * 1024 * 1024;

		function addUploadBoard(file, config, key, type) {
			var id = file.id;
			if(file.size > 100 * 1024 * 1024) {
				$api.showtoast("最大上传文件100M,请不要超过哦！");
				return "";
			}
			var count = Math.ceil(file.size / BLOCK_SIZE);
			var rowLi = $(".record_row").html();
			var filesize = 0;
			if(file.size < 1024)
				filesize = file.size + "字节";
			else if(file.size < (1024 * 1024)) {
				filesize = (file.size / 1024).toFixed(2) + "K";
			} else
				filesize = (file.size / 1024 / 1024).toFixed(2) + "M";
			var newobj = {
				"Fname": key,
				"Fsize": filesize,
				"Fpg": 'pg_' + id,
				"liid": 'li_' + id
			};

			var obj = $api.formatTemplate(newobj, rowLi);

			$(".record").append(obj);
			return $(".record").find('#li_' + id);
		}

		function initUpView() {
			var uploadUrl = qiniu.getUploadUrl(config, token);

			var indexCount = 0;
			var resume = false;
			var chunk_size;
			var blockSize;
			var uploader = new plupload.Uploader({
				runtimes: "html5,flash,silverlight,html4",
				url: uploadUrl,
				browse_button: "select", // 触发文件选择对话框的按钮，为那个元素id
				flash_swf_url: "./js/Moxie.swf", // swf文件，当需要使用swf方式进行上传时需要配置该参数
				silverlight_xap_url: "./js/Moxie.xap",
				chunk_size: BLOCK_SIZE,
				max_retries: 3,
				filters: {
					mime_types: [ //只允许上传图片和zip文件
						{
							title: "Vedio files",
							extensions: "jpg,jpge,png,gif,bmp"
						}
					],
					max_file_size: '10240kb', //最大只能上传400kb的文件
					prevent_duplicates: true //不允许选取重复文件
				},
				multipart_params: {
					// token从服务端获取，没有token无法上传
					token: token
				},
				init: {
					PostInit: function() {
						console.log("upload init");
					},
					FilesAdded: function(up, files) {
						resume = false;
						chunk_size = uploader.getOption("chunk_size");
						var id = files[0].id;
						// 添加上传dom面板
						$("#alarm2").css("display", "none");

						board[id] = addUploadBoard(files[0], config, files[0].name, "2");
						uploader.start();

					},
					FileUploaded: function(up, file, info) {
						console.log(info);
					},
					UploadComplete: function(up, files) {
						// Called when all files are either uploaded or failed
						console.log("[完成]");
					},
					Error: function(up, err) {
						console.log(err.response);
					}
				}
			});
			uploader.init();
			uploader.bind('Error', function() {
				console.log(1234)
			})
			uploader.bind("BeforeUpload", function(uploader, file) {
				key = file.name;
				putExtra.params["x:name"] = key.split(".")[0];
				var id = file.id;
				chunk_size = uploader.getOption("chunk_size");
				var directUpload = function() {
					var multipart_params_obj = {};
					multipart_params_obj.token = token;
					// filterParams 返回符合自定义变量格式的数组，每个值为也为一个数组，包含变量名及变量值
					var customVarList = qiniu.filterParams(putExtra.params);
					for(var i = 0; i < customVarList.length; i++) {
						var k = customVarList[i];
						multipart_params_obj[k[0]] = k[1];
					}
					multipart_params_obj.key = key;
					uploader.setOption({
						url: uploadUrl,
						multipart: true,
						multipart_params: multipart_params_obj
					});
				};

				var resumeUpload = function() {
					blockSize = chunk_size;
					initFileInfo(file);
					if(blockSize === 0) {
						mkFileRequest(file)
						uploader.stop()
						return
					}
					resume = true;
					var multipart_params_obj = {};
					// 计算已上传的chunk数量
					var index = Math.floor(file.loaded / chunk_size);

					var headers = qiniu.getHeadersForChunkUpload(token)
					uploader.setOption({
						url: uploadUrl + "/mkblk/" + blockSize,
						multipart: false,
						required_features: "chunks",
						headers: {
							Authorization: "UpToken " + token
						},
						multipart_params: multipart_params_obj
					});
				};
				// 判断是否采取分片上传
				if(
					(uploader.runtime === "html5" ||
						uploader.runtime === "flash") &&
					chunk_size
				) {
					if(file.size < chunk_size) {
						directUpload();
					} else {
						resumeUpload();
					}
				} else {
					console.log(
						"directUpload because file.size < chunk_size || is_android_weixin_or_qq()"
					);
					directUpload();
				}
			});

			uploader.bind("ChunkUploaded", function(up, file, info) {
				var res = JSON.parse(info.response);
				var leftSize = info.total - info.offset;
				var chunk_size = uploader.getOption && uploader.getOption("chunk_size");
				if(leftSize < chunk_size) {
					up.setOption({
						url: uploadUrl + "/mkblk/" + leftSize
					});
				}
				up.setOption({
					headers: {
						Authorization: "UpToken " + token
					}
				});
				// 更新本地存储状态
				var localFileInfo = JSON.parse(localStorage.getItem(file.name)) || [];
				localFileInfo[indexCount] = {
					ctx: res.ctx,
					time: new Date().getTime(),
					offset: info.offset,
					percent: file.percent
				};
				indexCount++;
				localStorage.setItem(file.name, JSON.stringify(localFileInfo));
			});

			// 每个事件监听函数都会传入一些很有用的参数，
			// 我们可以利用这些参数提供的信息来做比如更新UI，提示上传进度等操作
			uploader.bind("UploadProgress", function(uploader, file) {
				var id = file.id;
				// 更新进度条进度信息;
				var fileUploaded = file.loaded || 0;
				$(board[id]).find('#pg_' + id).css("width", file.percent + "%");
				$(board[id]).find('#pg_' + id).find("span").text(file.percent + "%");
			});

			uploader.bind("FileUploaded", function(uploader, file, info) {
				var id = file.id;
				if(resume) {
					mkFileRequest(file)
				} else {
					$(board[id]).find('#pg_' + id).css("width", "100%");
					$(board[id]).find('#pg_' + id).find("span").text("100%");
					uploadFinish(JSON.parse(info.response), file, board[id]);
				}
			});

			function uploadFinish(res, file, board) {
				var name = file.name;
				localStorage.removeItem(name);
				var path = domain + res.key;
				saveInfo(file, path);
				for(var i = 1; i < 6; i++) {
					var src = $("#Img" + i).attr("src");
					if(src == "") {
						$("#Img" + i).attr("src", path+small);
						$("#Img" + i).css('display', 'block');
						$("#imgdel" + i).css('display', 'block');
						break;;
					}
				}
			}

			function saveInfo(file, path) {
				var url = BaseUrl + "Attach?token=" + $api.getStorage("token") + "&action=add";

				var param = {
					Fpath: path,
					Fatid: comboxDefault,
					Ftype: 0,
					Fname: file.name,
					Fsize: file.size
				}
				$api.ajaxapp2(url, param, function(data) {

				});
			}

			function initFileInfo(file) {
				var localFileInfo = JSON.parse(localStorage.getItem(file.name)) || [];
				indexCount = 0;
				var length = localFileInfo.length
				if(length) {
					var clearStatus = false
					for(var i = 0; i < localFileInfo.length; i++) {
						indexCount++
						if(isExpired(localFileInfo[i].time)) {
							clearStatus = true
							localStorage.removeItem(file.name);
							break;
						}
					}
					if(clearStatus) {
						indexCount = 0;
						return
					}
					file.loaded = localFileInfo[length - 1].offset;
					var leftSize = file.size - file.loaded;
					if(leftSize < chunk_size) {
						blockSize = leftSize
					}
					file.percent = localFileInfo[length - 1].percent;
					return
				} else {
					indexCount = 0
				}
			}

			function mkFileRequest(file) {
				// 调用sdk的url构建函数
				var requestUrl = qiniu.createMkFileUrl(
					uploadUrl,
					file.size,
					key,
					putExtra
				);
				var ctx = []
				var id = file.id
				var local = JSON.parse(localStorage.getItem(file.name))
				for(var i = 0; i < local.length; i++) {
					ctx.push(local[i].ctx)
				}
				// 设置上传的header信息
				var headers = qiniu.getHeadersForMkFile(token)
				$.ajax({
					url: requestUrl,
					type: "POST",
					headers: headers,
					data: ctx.join(","),
					success: function(res) {
						uploadFinish(res, file.name, board[id]);
					}
				})
			}

			function isExpired(time) {
				var expireAt = time + 3600 * 24 * 1000;
				return new Date().getTime() > expireAt;
			}
		}
		//////////////////////////////////////////////////////////////
		function initImgListNet() {
			var url = attrUrl + "&Fatyid=" + comboxDefault;
			$(".imglist ul").html('');
			total_q = 0;
			total_page = 0;
			showFootDiv();
			$api.ajaxget(url, {}, function(result) {
				total_q = result.Total;
				if(total_q == 0) {
					$(".record").html("");
					$("#alarm").css("display", "block");
					$(".imglist").css("display", "none");
					$("#PageContent").css("display", "none");

					return;
				} else {
					$("#alarm").css("display", "none");
					$(".imglist").css("display", "block");
					$("#PageContent").css("display", "block");
				}
				if(total_q < current_page) total_page = 0;
				else {
					total_page = Math.round(total_q / current_page); //总页数  
					if(total_q % current_page != 0) total_page++;
				}
				var html = "";
				for(var i = 0; i < result.Rows.length; i++) {
					var item = result.Rows[i];

					var osrc = item.Fpath+ small;
					html += "<li><div class=\"details\"><div class=\"pic\">";
					html += "<img style='object-fit:contain' src=\"" + osrc + "\"    /></div></div></li>";
				}
				$(".imglist ul").html(html);
				//图片延迟加载
				$(".pic img").lazyload({
					load: AutoResizeImage,
					effect: "fadeIn"
				});

				//点击图片链接
				$(".pic img").click(function() {
					for(var i = 1; i < 6; i++) {
						var src = $("#Img" + i).attr("src");
						if(src == "") {
							$("#Img" + i).attr("src", $(this).attr("src"));
							$("#Img" + i).css('display', 'block');
							$("#imgdel" + i).css('display', 'block');
							isFind = true;
							break;;
						}
					}

				});
				$(".imglist ul li:gt(" + (current_page - 1) + ")").hide();
				showFootDiv();
			});

		}

		var current_page = 20; //每页显示的数据
		var total_q = 0; //总数据
		var current_num = 1; //当前页数
		var total_page = 0;
		var centSize = 8;

		function showFootDiv() {
			//计算页数
			if(total_q < 1 || total_page < 1) {
				return "";
			}
			var firstStr = "";
			var lastStr = "";
			var firstBtn = "<a  onclick='showPage(1)'>上一页</a>";
			var lastBtn = "<a onclick='showPage(" + (current_num + 1) + ")'>下一页</a>";

			if(current_num <= 1) {
				firstBtn = "<span class=\"disabled\">上一页</span>";
			}
			if(current_num >= total_page) {
				lastBtn = "<span class=\"disabled\">下一页</span>";
			}
			if(current_num == 1) {
				firstStr = "<span class=\"current\">1</span>";
			}
			if(current_num == total_page) {
				lastStr = "<span class=\"current\">" + total_page + "</span>";
			}
			var firstNum = current_num - (centSize / 2); //中间开始的页码
			if(current_num < centSize)
				firstNum = 2;
			var lastNum = current_num + centSize - ((centSize / 2) + 1); //中间结束的页码
			if(lastNum >= total_page)
				lastNum = total_page - 1;
			var pageStr = "";

			pageStr += firstBtn + firstStr;
			if(current_num >= centSize) {
				pageStr += "<span>...</span>\n";
			}
			for(var i = firstNum; i <= lastNum; i++) {
				if(i == current_num) {
					pageStr += "<span class=\"current\">" + i + "</span>";
				} else {
					pageStr += "<a  onclick='showPage(" + i + ")'>" + i + "</a>";
				}
			}
			if(total_page - current_num > centSize - ((centSize / 2))) {
				pageStr += "<span>...</span>";
			}
			pageStr += lastStr + lastBtn;
			pageStr += "<span>共" + total_q + "张</span>";
			$("#PageContent").html(pageStr);
		}

		function showPage(pageNo) {

			current_num = pageNo;
			showFootDiv();
			//下一页 
			$.each($('.imglist ul li'), function(index, item) {
				var start = current_page * (current_num - 1); //起始范围
				var end = current_page * current_num; //结束范围
				if(index >= start && index < end) { //如果索引值是在start和end之间的元素就显示，否则就隐
					$(this).show();
				} else {
					$(this).hide();
				}
			});
		}

		//排列图文列表
		function imgLayout() {
			var imgWidth = $(".imglist").width();
			var lineCount = Math.floor(imgWidth / 53);
			var lineNum = imgWidth % 53 / (lineCount - 1);
			$(".imglist ul").width(imgWidth + Math.ceil(lineNum));
			$(".imglist ul li").css("margin-right", parseFloat(lineNum));
		}
		//等比例缩放图片大小
		function AutoResizeImage(e, s) {
			var img = new Image();
			img.src = $(this).attr("src")
			var w = img.width;
			var h = img.height;
			var wRatio = w / h;
			if((53 / wRatio) >= 53) {
				$(this).width(53);
				$(this).height(36 / wRatio);
			} else {
				$(this).width(53 * wRatio);
				$(this).height(53);
			}
		}

		function createphotos() {
			key = "";
			top.$.ligerDialog.open({
				zindex: 1000,
				width: 320,
				height: 140,
				title: '相册创建',
				url: 'vcommon/common/CreatePhotoDialog.html',
				buttons: [{
						text: '确定',
						onclick: function(item, dialog) {
							var issave = dialog.frame.f_save();
							if(issave) {
								dialog.close();
								var url = attrTypeUrl + "&action=add";
								$api.ajaxapp2(url, issave, function(data) {
									managerSPhotos.reload()
									managerPhoto.reload();
								});

							}
						}
					},
					{
						text: '关闭',
						onclick: function(item, dialog) {
							dialog.close();
						}
					}
				],
				isResize: false,
				timeParmName: 'a'
			});
		}

		function getPhotos() {
			var photos = [];
			for(var i = 1; i < 6; i++) {
				var src = $("#Img" + i).attr("src");
				if(src != "") {
					photos.push(src);
				}
			}
			return photos.reverse();
		}

		function tabs(tabObj) {
			var tabNum = $(tabObj).parent().index("li")

			//设置点击后的切换样式
			$(tabObj).parent().parent().find("li a").removeClass("selected");
			$(tabObj).addClass("selected");
			//根据参数决定显示内容
			$(".tab-content").hide();
			$(".tab-content").eq(tabNum).show();
			if(tabNum == 1) {
				if(null == managerPhoto) {
					managerPhoto = $("#ddlCPhoto").ligerComboBox({
						url: attrTypeUrl,
						ajaxType: 'get',
						valueField: 'Fid',
						textField: 'Fname',
						values: comboxDefault,
						onSelected: function(newvalue) {
							comboxDefault = newvalue;
							managerSPhotos.setValue(comboxDefault);
							$api.setStorage(user.Fid + "_xc", newvalue);
						}
					});

				}
				managerPhoto.setValue(comboxDefault);
			}

		}

		function delImg(i) {
			$("#Img" + i).attr("src", "");
			$("#Img" + i).css('display', 'none');
			$("#imgdel" + i).css('display', 'none');
		}
	</script>

	<body class="mainbody2">
		<form id="form1">
			<!--导航栏-->
			<div class="location">
				<i class="arrow"></i>
				<span>选择您要添加的图片来源,【删除权限】系统设置》素材管理</span>
			</div>
			<div class="line5"></div>
			<div class="content-tab-wrap">
				<div  class="content-tab">
					<div class="content-tab-ul-wrap">
						<ul>
							<li>
								<a href="javascript:;" onclick="tabs(this);" class="selected">图片管家</a>
							</li>
							<li>
								<a href="javascript:;" onclick="tabs(this);">本地图片</a>
							</li>
						</ul>
					</div>
				</div>
			</div>
			<div class="tab-content" style="height:190px">
				<dl>
					<dt style="width:120px">选择相册</dt>
					<dd style="margin-left:140px;">
						<div style="float:left">
							<input type="text" id="ddlSPhotos" name="ddlSPhotos" ligerui="{width:160}" validate="{required:true}" />
						</div>
						<span style="float:left;margin-left:10px;">从图片管家中选取图片</span>
					</dd>
				</dl>

				<div id="alarm" style="height:150px;padding-top:45px;display:none;" align="center">
					<img src="../../css/skin/default/alarm.png" style="vertical-align:middle;width:20px;height:20px" />
					<span style="vertical-align:middle">该相册暂无图片<a style="color:#0063FD" onclick="tabs(1)">请先上传</a>，或选择其他相册。</span>
				</div>
				<!--图片列表-->
				<div class="imglist" style="height:120px">
					<ul>
					</ul>
				</div>
				<!--/图片列表-->
				<!--内容底部-->
				<div id="PageContent" class="default" align="right" style="padding-right:5px"></div>
				<!--/内容底部-->
			</div>
			<div class="tab-content" style="display:none;height:190px">
				<dl>
					<dt style="width:120px">选择相册</dt>
					<dd style="margin-left:140px;">
						<div style="float:left">
							<input id="ddlCPhoto" name="ddlCPhoto" ligerui="{width:160}" validate="{required:true}" /> </div>
						<a style="float:left;margin-left:10px;cursor:pointer" onclick="createphotos();"><span>创建相册</span></a>
					</dd>
				</dl>
				<dl>
					<dt style="width:120px"></dt>
					<dd style="margin-left:140px;">
						<div id="select" class="btn green">图片上传</div>
					</dd>
				</dl>
				<div id="alarm2" style="margin-left:60px;padding:20px 0;">
					提示：您最多一次可以上传5张图片，选择的图片单张大小不超过5MB，支持jpg,jpeg,bmp,png。
				</div>
				<div style="width:100%;">
					<ul class="record">

					</ul>
				</div>
			</div>
			<div style="padding:5px 0px 0px 0px">
				<table>
					<tr>
						<td>
							<div class="picNumContainer">
								<span>1</span>
								<img id="Img1" src="" class="imgs" />
								<img id="imgdel1" src="../../img/common_delete.png" class="closeimg" onclick="delImg(1);" />
							</div>
						</td>
						<td>
							<div class="picNumContainer">
								<span>2</span>
								<img id="Img2" src="" class="imgs" />
								<img id="imgdel2" src="../../img/common_delete.png" class="closeimg" onclick="delImg(2);" />
							</div>
						</td>
						<td>
							<div class="picNumContainer">
								<span>3</span>
								<img id="Img3" src="" class="imgs" />
								<img id="imgdel3" src="../../img/common_delete.png" class="closeimg" onclick="delImg(3);" />
							</div>
						</td>
						<td>
							<div class="picNumContainer">
								<span>4</span>
								<img id="Img4" src="" class="imgs" />
								<img id="imgdel4" src="../../img/common_delete.png" class="closeimg" onclick="delImg(4);" />
							</div>
						</td>
						<td>
							<div class="picNumContainer">
								<span>5</span>
								<img id="Img5" src="" class="imgs" />
								<img id="imgdel5" src="../../img/common_delete.png" class="closeimg" onclick="delImg(5);" />
							</div>
						</td>
					</tr>
				</table>
			</div>
		</form>
	</body>

</html>